﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2017/7/4
 * 时间: 0:30
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Net;
using System.IO;
using System.Text;

namespace TIDTool
{
	/// <summary>
	/// Description of BaiduTTS.
	/// </summary>
	public class BaiduTTS
	{
		HttpWebRequest httpReq;
		string accessToken;
		
		public BaiduTTS()
		{
			accessToken = "";
			GetAuthToken("自己的KEY自己填写", "自己的KEY自己填写");
		}
		
		public bool GetAuthToken(string apiKey, string secretKey)
		{
			string postStr = "grant_type=client_credentials" + 
				"&client_id=" + apiKey + 
				"&client_secret=" + secretKey;
			byte[] postData = Encoding.Default.GetBytes(postStr);
			
			httpReq = (HttpWebRequest)WebRequest.Create("https://openapi.baidu.com/oauth/2.0/token");
			httpReq.Method = "POST";
			httpReq.ContentLength = postData.Length;  
			Stream requestStream = httpReq.GetRequestStream();  
			requestStream.Write(postData, 0, postData.Length);  
			  
			HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse();  
			Stream responseStream = response.GetResponseStream();
			StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
			string str = sr.ReadToEnd();
			sr.Close();
			responseStream.Close();
			
//			"access_token": "1.a6b7dbd428f731035f771b8d********.86400.1292922000-2346678-124328",
			int pos1 = str.IndexOf("access_token");
			if (pos1 > 0)
			{
				pos1 += "access_token".Length + 1;
				pos1 = str.IndexOf('"', pos1);
				pos1++;
				int pos2 = str.IndexOf('"', pos1);
				accessToken = str.Substring(pos1, pos2 - pos1);
				return true;
			}
			return false;
		}
		
		public byte[] GetVoice(string str)
		{
//			tex	必填	合成的文本，使用UTF-8编码，请注意文本长度必须小于1024字节
//			lan	必填	语言选择,目前只有中英文混合模式，填写固定值zh
//			tok	必填	开放平台获取到的开发者 access_token
//			ctp	必填	客户端类型选择，web端填写固定值1
//			cuid	必填	用户唯一标识，用来区分用户，计算UV值。建议填写能区分用户的机器 MAC 地址或 IMEI 码，长度为60字符以内。
			string postStr = "tex=" + str + 
				"&lan=zh&ctp=1&cuid=1234567890ab" + 
				"&tok=" + accessToken;
			byte[] postData = Encoding.UTF8.GetBytes(postStr);
			
			httpReq = (HttpWebRequest)WebRequest.Create("http://tsn.baidu.com/text2audio");
			httpReq.Method = "POST";
			httpReq.ContentLength = postData.Length;  
			Stream requestStream = httpReq.GetRequestStream();  
			requestStream.Write(postData, 0, postData.Length);  
			  
			HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse();  
			Stream responseStream = response.GetResponseStream();
			int dataLen = (int)response.ContentLength;
			BinaryReader br = new BinaryReader(responseStream);
			byte[] data = br.ReadBytes(dataLen);
			responseStream.Close();
			
			return data;
		}
	}
}
